package cn.nfwx.tv.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.chan.net.HttpCallback;
import com.chan.net.Result;
import com.flyco.tablayout.SlidingTabLayout;
import com.squareup.haha.guava.collect.ArrayListMultimap;

import org.yczbj.ycvideoplayerlib.controller.VideoPlayerController;
import org.yczbj.ycvideoplayerlib.manager.VideoPlayerManager;
import org.yczbj.ycvideoplayerlib.player.VideoPlayer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.CategoryAdapter;
import cn.nfwx.tv.base.BaseActivity;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.manager.NyqfManager;
import cn.nfwx.tv.model.NyqfBean;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.StatusBarUtil;
import cn.nfwx.tv.widget.LoadView;
import cn.nfwx.tv.widget.NavigationTabView;

public class CcpActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.main_abl_appbar)
    AppBarLayout mainAblAppbar;
    @BindView(R.id.ll_cpp_buttom)
    LinearLayout llCppButtom;
    @BindView(R.id.rb_cpp_main)
    NavigationTabView rbCppMain;
    @BindView(R.id.rb_cpp_dang)
    NavigationTabView rbCppDang;
    @BindView(R.id.rb_cpp_mine)
    NavigationTabView rbCppMine;

    @BindView(R.id.rcy_main)
    SlidingTabLayout rcyMain;
    @BindView(R.id.main_vp)
    ViewPager mainVp;
    @BindView(R.id.fl_content)
    FrameLayout flContent;

    LoadView loadView;

    //    List<BaseFragment> fragmentList;
    List<NavigationTabView> navigationTabViewList;

    int select = -1;

    final String FIRST_INDEX = "index";
    final String SECEND_INDEX = "dangjian";
    final String THIRD_INDEX = "me";

    public final static String ACTION_RELOAD_CHANNEL = "ACTION_RELOAD_CHANNEL";

    ArrayListMultimap<String, NyqfBean.DataBean> listMultimap;
    private CategoryAdapter adapter;

    private VideoPlayer mVideoView;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CcpActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ccp;
    }

    private void initTabIndicator() {
        adapter = new CategoryAdapter(getSupportFragmentManager());
        mainVp.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        if (VideoPlayerManager.instance().onBackPressed()) return;
        super.onBackPressed();
    }

    public VideoPlayer getVideoView() {
        if (mVideoView == null) {
            mVideoView = new VideoPlayer(mContext);
            VideoPlayerController controller = new VideoPlayerController(mContext);
            controller.setTitle("");
            mVideoView.setController(controller);
        }
        return mVideoView;
    }

    @Override
    protected void bindView() {
        ButterKnife.bind(this);
        StatusBarUtil.compat(this, Color.parseColor("#FF4040"));

        listMultimap = ArrayListMultimap.create();

        rbCppMain.setRadioButtonBG(R.mipmap.main_selected, R.mipmap.main_unselected, "首页");
        rbCppDang.setRadioButtonBG(R.mipmap.nyqf_selected, R.mipmap.nyqf_unselected, "反腐倡廉");
        rbCppMine.setRadioButtonBG(R.mipmap.me_selected, R.mipmap.me_unselected, "我");
        navigationTabViewList = Arrays.asList(rbCppMain, rbCppDang, rbCppMine);


        //initTabIndicator();
        loadView = new LoadView(mContext);

        initTabIndicator();
        select(0);
    }

    @Override
    protected void initData() {
        loadView.startLoading(flContent);
        NyqfManager.getnyqfTitles(this.<Result<NyqfBean>>bindToLifecycle(), new HttpCallback<NyqfBean>() {
            @Override
            public void onSuccess(String requestCommand, Result<NyqfBean> data) {
                NyqfBean bean = data.getData();
                for (NyqfBean.NavBean navBean : bean.getNav()) {
                    initIndex(navBean);
                }
                initMeIndex();
                bindDataView();
            }

            @Override
            public void onFail(String requestCommand, Result result) {

            }
        });
    }

    /**
     * 绑定数据to View
     */
    private void bindDataView() {
        final int position = (select == -1) ? 0 : select;
        loadView.removeParentView(flContent);
        select = -1;
        select(position);
    }


    /**
     * 页面标题处理
     *
     * @param navBean
     */
    private void initIndex(NyqfBean.NavBean navBean) {
        if (navBean.getCode().equalsIgnoreCase(FIRST_INDEX)) {
            initFirstIndex(navBean);
        } else {
            initOthersIndex(navBean);
        }
    }

    /**
     * 首页
     *
     * @param navBean
     */
    private void initFirstIndex(NyqfBean.NavBean navBean) {
        List<NyqfBean.DataBean> dataBeans = new ArrayList<>(navBean.getData());
        dataBeans.addAll(Arrays.asList(new NyqfBean.DataBean("", "直播"), new NyqfBean.DataBean("", "视频")));
        for (NyqfBean.DataBean dataBean : dataBeans) {
            listMultimap.put(FIRST_INDEX, dataBean);
        }
    }

    /**
     * 其他页面
     *
     * @param navBean
     */
    private void initOthersIndex(NyqfBean.NavBean navBean) {
        for (NyqfBean.DataBean dataBean : navBean.getData()) {
            listMultimap.put(navBean.getCode(), dataBean);
        }
    }

    /**
     * 我的页面
     */
    private void initMeIndex() {
        NyqfBean.DataBean dataBean = new NyqfBean.DataBean();
        dataBean.setTitle("我");
        listMultimap.put(THIRD_INDEX, dataBean);
    }

    void select(int position) {
        if (select != position) {
            select = position;
            for (NavigationTabView navigationTabView : navigationTabViewList) {
                navigationTabView.setCheck(false);
            }
            navigationTabViewList.get(position).setCheck(true);
            bindTitle(position);
        }
    }

    void bindTitle(int position) {
        if (listMultimap.size() > 0) {
            List<NyqfBean.DataBean> dataBeans = null;
            switch (position) {
                case 0:
                    dataBeans = listMultimap.get(FIRST_INDEX);
                    break;
                case 1:
                    dataBeans = listMultimap.get(SECEND_INDEX);
                    break;
                case 2:
                    dataBeans = listMultimap.get(THIRD_INDEX);
                    break;
            }
            if (dataBeans != null && !dataBeans.isEmpty()) {
                String[] strings = new String[dataBeans.size()];
                for (int i = 0; i < dataBeans.size(); i++) {
                    strings[i] = dataBeans.get(i).getTitle();
                }
                mainVp.setOffscreenPageLimit(dataBeans.size());
                adapter.setNewData(dataBeans);
                rcyMain.setViewPager(mainVp, strings);
                rcyMain.setCurrentTab(0, false);
                mainVp.removeOnPageChangeListener(CcpActivity.this);
                mainVp.addOnPageChangeListener(CcpActivity.this);
            }
        }
    }

    @Override
    protected String activityName() {
        return CcpActivity.class.getSimpleName();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        listMultimap.clear();
        removePlayerView();
        mVideoView = null;
        mainVp.removeOnPageChangeListener(CcpActivity.this);
    }

    @OnClick({R.id.rb_cpp_main, R.id.rb_cpp_dang, R.id.rb_cpp_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_cpp_main:
                select(0);
                break;
            case R.id.rb_cpp_dang:
                select(1);
                break;
            case R.id.rb_cpp_mine:
                select(2);
                break;
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Looper.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    removePlayerView();
                    return false;
                }
            });
        } else {
            removePlayerView();
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    /**
     * 清除videoView的父view
     */
    public void removePlayerView() {
        if (mVideoView == null) {
            return;
        }
        if (mVideoView.getParent() != null) {
            ViewGroup viewGroup = (ViewGroup) mVideoView.getParent();
            viewGroup.removeView(mVideoView);
        }
        mVideoView.release();
        VideoPlayerManager.instance().releaseVideoPlayer();
    }

    /**
     * 是否有父view
     *
     * @return
     */
    public boolean hasVideoViewParent() {
        if (mVideoView == null) {
            return false;
        } else {
            if (mVideoView.getParent() != null) {
                return true;
            }
            return false;
        }
    }
}
